package com.sxw.springbootproducer.service;

import com.sxw.entity.BrokerMessageLog;
import com.sxw.entity.Order;
import com.sxw.springbootproducer.constant.Constants;
import com.sxw.springbootproducer.mapper.BrokerMessageLogMapper;
import com.sxw.springbootproducer.mapper.OrderMapper;
import com.sxw.springbootproducer.producer.RabbitOrderSender;
import com.sxw.springbootproducer.utils.DateUtils;
import com.sxw.springbootproducer.utils.FastJsonConvertUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

@Service
public class OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private BrokerMessageLogMapper brokerMessageLogMapper;

    @Autowired
    private RabbitOrderSender rabbitOrderSender;

    @Transactional(rollbackFor = Exception.class)
    public Boolean createOrder(Order order) throws Exception {
        // 插入业务数据
        int OrderInsertMark = orderMapper.insert(order);
        if(OrderInsertMark != 1){
            throw new Exception("创建订单-订单信息插入失败");
        }

        // 新建消息记录
        BrokerMessageLog brokerMessageLog = new BrokerMessageLog();
        // 消息唯一ID（业务关联主键）
        brokerMessageLog.setMessageId(order.getMessageId());
        // 保存消息整体 转为JSON 格式存储入库
        brokerMessageLog.setMessage(FastJsonConvertUtil.convertObjectToJSON(order));
        // 设置重试次数为0
        brokerMessageLog.setTryCount(0);
        // 设置消息状态为0 表示发送中
        brokerMessageLog.setStatus("0");
        // 使用当前时间当做订单创建时间（为了模拟一下简化），设置消息未确认超时时间窗口为 一分钟
        Date orderTime = new Date();
        brokerMessageLog.setNextRetry(DateUtils.addMinutes(orderTime, Constants.ORDER_TIMEOUT));
        // 初始化时间凭证
        brokerMessageLog.setCreateTime(new Date());
        brokerMessageLog.setUpdateTime(new Date());
        // 插入消息记录表数据
        int brokerMessageLogInsertMark = brokerMessageLogMapper.insertSelective(brokerMessageLog);
        if(OrderInsertMark != 1){
            throw new Exception("创建订单-消息记录插入失败");
        }

        // 发送消息
        rabbitOrderSender.sendOrder(order);

        return true;
    }

}

